package com.jacky.iot.callback;

import com.jacky.iot.mediators.ReconnectEvent;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

@Component
public class ClientCallback implements MqttCallback {

    private final static Logger log = LoggerFactory.getLogger(ClientCallback.class);
    private final ApplicationEventPublisher publisher;
    //    private final Mediator mediator;
//
//    public ClientCallback(Mediator mediator) {
//        this.mediator = mediator;
//    }

    public ClientCallback(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }


    @Override
    public void connectionLost(Throwable throwable) {
        log.error("connectionLost:", throwable);
//        mediator.trigger();
        publisher.publishEvent(new ReconnectEvent("connect lost"));
    }

    @Override
    public void messageArrived(String topic, MqttMessage msg) throws Exception {
        log.info("topic:{}, msgId:{}, qos:{}, isDup:{}, isRetain:{}, payLoad:{}",
                topic, msg.getId(), msg.getQos(),
                msg.isDuplicate(), msg.isRetained(), msg);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        try {
            log.info("receive Qos2(PUBCOMP) callback msgId:{},payLoad:{} ", token.getMessageId(), token.getMessage());
            int id = token.getMessage().getId();
        } catch (MqttException e) {
            log.error("mqtt delivery comp exception:", e);
        }
    }
}
